package com.example.netty.handler;

import com.example.netty.bean.ResMsg;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.CharBuffer;
import java.nio.charset.Charset;

/**
 * @author: lichong
 * @Date: 2020/1/20 13:49
 * @Description: 信息编码
 */
public class MessageEncoder extends MessageToByteEncoder<Object> {

    private static final Charset charset = Charset.forName("utf-8");

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object resMsg, ByteBuf byteBuf) throws Exception {
        if (resMsg != null) {
            String msgBody = "";
            if (resMsg instanceof ResMsg) {
                msgBody = ((ResMsg)resMsg).getMsgBody();
            } else {
                msgBody = (String) resMsg;
            }
            byteBuf.writeBytes(ByteBufUtil.encodeString(channelHandlerContext.alloc(), CharBuffer.wrap(msgBody), charset));
        }
    }
}
